'''Functions to parse a configuration file used to hold inputs for
the script that creates an HDF5 file of dust events.

Mike Dorey  2011-04-04
'''


def is_blank(line):
    '''Returns True if the line is nothing but white space.

    Argument
        line - line from a configuration file
    '''
    return len(line.strip()) == 0


def is_comment(line):
    '''Returns True if the line holds nothing but a comment.
    A comment begins with the character '#'.

    Argument
        line - line from a configuration file
    '''
    return line.strip().startswith('#')
    

def strip_comment(line):
    '''Strips any existing comment from the end of the line.

    Argument
        line - line from a configuration file
    '''
    before,sharp,comment = line.partition('#')
    return before


def parse(filename):
    '''Parses the configuration file and returns a dictionary of
    the key/value pairs.

    Argument
        filename - name of a configuration file
    '''
    lines = [l.strip() for l in open(filename)]
    lines = [l for l in lines if not is_blank(l)]
    lines = [l for l in lines if not is_comment(l)]
    lines = [strip_comment(l) for l in lines]
    dct = {}
    for l in lines:
        key,equal_sign,value = l.partition('=')
        dct[key.strip().lower()] = value.strip()
    return dct
